package cool.doudou.doudada.mqtt.core.factory;

import cool.doudou.doudada.mqtt.core.method.SubscribeMethod;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * MethodMapFactory
 *
 * @author jiangcs
 * @since 2022/3/3
 */
public class MethodMapFactory {
    private static final Map<String, SubscribeMethod> map = new ConcurrentHashMap<>();

    public static SubscribeMethod get(String topic) {
        SubscribeMethod subscribeMethod = map.get(topic);
        if (subscribeMethod != null) {
            return subscribeMethod;
        }

        for (String t : map.keySet()) {
            if (t.endsWith("/+") || t.endsWith("/#")) {
                if (topic.startsWith(t.replaceAll("\\+", "").replaceAll("#", ""))) {
                    return map.get(t);
                }
            }
        }
        return null;
    }

    public static void add(String topic, SubscribeMethod method) {
        map.put(topic, method);
    }
}
